<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑员工' : '新增员工'"
    width="700px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="localFormData"
      :rules="formRules"
      label-width="100px"
      label-position="right"
      class="employee-form"
    >
      <!-- 第一行：员工姓名和性别 -->
      <div class="form-row">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="name">
              <el-input
                v-model="localFormData.name"
                placeholder="请输入员工姓名"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="localFormData.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 第二行：身份证号和部门 -->
      <div class="form-row">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input
                v-model="localFormData.idNumber"
                placeholder="请输入身份证号"
                maxlength="18"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-select
                v-model="localFormData.deptId"
                placeholder="请选择部门"
                style="width: 100%"
                :loading="deptLoading"
              >
                <el-option
                  v-for="dept in departmentOptions"
                  :key="dept.id"
                  :label="dept.deptName"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 第三行：职位和职级 -->
      <div class="form-row">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input
                v-model="localFormData.position"
                placeholder="请输入职位"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职级" prop="jobLevel">
              <el-input
                v-model="localFormData.jobLevel"
                placeholder="请输入职级"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 第四行：入职日期和在职状态 -->
      <div class="form-row">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入职日期" prop="hireDate">
              <el-date-picker
                v-model="localFormData.hireDate"
                type="date"
                placeholder="选择入职日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在职状态" prop="workState">
              <el-select
                v-model="localFormData.workState"
                placeholder="请选择在职状态"
                style="width: 100%"
              >
                <el-option label="在职" :value="1" />
                <el-option label="离职" :value="2" />
                <el-option label="休假" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 第五行：联系电话和邮箱 -->
      <div class="form-row">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input
                v-model="localFormData.contactPhone"
                placeholder="请输入联系电话"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="contactEmail">
              <el-input
                v-model="localFormData.contactEmail"
                placeholder="请输入邮箱"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 第六行：头像URL -->
      <div class="form-row">
        <el-form-item label="头像URL" prop="avatar">
          <el-input
            v-model="localFormData.avatar"
            placeholder="请输入头像URL"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose" :disabled="loading">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="loading"
        >
          {{ loading ? '提交中...' : '确定' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { employeeApi } from '@/api/employee'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  departmentOptions: {
    type: Array,
    default: () => []
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

// 响应式数据
const dialogVisible = ref(false)
const loading = ref(false)
const deptLoading = ref(false)
const formRef = ref()

// 默认表单数据
const defaultFormData = {
  name: '',
  gender: 1,
  idNumber: '',
  deptId: null,
  position: '',
  jobLevel: '',
  hireDate: '',
  workState: 1,
  contactPhone: '',
  contactEmail: '',
  avatar: ''
}

// 本地表单数据
const localFormData = ref({ ...defaultFormData })

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '员工姓名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  idNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { 
      pattern: /^\d{17}[\dXx]$/,
      message: '身份证号格式不正确',
      trigger: 'blur'
    }
  ],
  deptId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  position: [
    { 
      required: true, 
      message: '请输入职位', 
      trigger: 'blur' 
    },
    {
      max: 50,
      message: '职位名称不能超过50个字符',
      trigger: 'blur'
    }
  ],
  jobLevel: [
    {
      max: 50,
      message: '职级不能超过50个字符',
      trigger: 'blur'
    }
  ],
  hireDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ],
  workState: [
    { required: true, message: '请选择在职状态', trigger: 'change' }
  ],
  contactPhone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  contactEmail: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: 'blur'
    }
  ]
}

// 监听props变化
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    nextTick(() => {
      resetForm()
      initializeFormData()
    })
  }
})

// 监听dialogVisible变化
watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 初始化表单数据
const initializeFormData = () => {
  if (props.isEdit && props.formData) {
    // 编辑模式：使用传入的数据
    const formData = {
      ...defaultFormData,
      ...props.formData
    }
    // 确保日期格式正确
    if (formData.hireDate) {
      formData.hireDate = formatDateForPicker(formData.hireDate)
    }
    localFormData.value = { ...formData }
  } else {
    // 新增模式：重置为默认值
    localFormData.value = { ...defaultFormData }
  }
}

// 格式化日期用于日期选择器
const formatDateForPicker = (dateString) => {
  if (!dateString) return ''
  try {
    let date
    if (typeof dateString === 'string') {
      if (dateString.includes('T')) {
        date = new Date(dateString)
      } else if (dateString.includes(' ')) {
        date = new Date(dateString.replace(' ', 'T'))
      } else {
        date = new Date(dateString)
      }
    } else {
      date = new Date(dateString)
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    
    return `${year}-${month}-${day}`
  } catch (e) {
    console.error('日期格式化错误:', e)
    return dateString
  }
}

// 重置表单验证
const resetForm = () => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleClose = () => {
  if (loading.value) {
    ElMessage.warning('正在提交，请稍候...')
    return
  }
  
  dialogVisible.value = false
  // 延迟重置表单，避免动画卡顿
  setTimeout(() => {
    localFormData.value = { ...defaultFormData }
  }, 300)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) {
    ElMessage.error('表单引用不存在')
    return
  }

  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }

    loading.value = true

    // 准备提交数据 - 确保日期格式正确
    const submitData = { 
      ...localFormData.value
    }

    // 清理空值
    Object.keys(submitData).forEach(key => {
      if (submitData[key] === '' || submitData[key] === undefined) {
        submitData[key] = null
      }
    })

    let response
    if (props.isEdit) {
      response = await employeeApi.updateEmployee(submitData)
    } else {
      response = await employeeApi.addEmployee(submitData)
    }

    // 判断响应结果
    if (response.code === 1) {
      ElMessage.success(props.isEdit ? '更新员工成功' : '新增员工成功')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (error) {
    if (error.errors) {
      // 表单验证错误，Element Plus 会自动显示错误信息
      return
    }
    
    // 网络错误或其他异常
    if (error.response) {
      ElMessage.error(`服务器错误: ${error.response.data?.msg || error.response.status}`)
    } else if (error.request) {
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      ElMessage.error('操作失败: ' + error.message)
    }
  } finally {
    loading.value = false
  }
}

// 暴露方法给父组件
defineExpose({
  resetForm,
  handleClose
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
}

/* 表单间距调整 */
:deep(.employee-form) {
  padding: 10px 0;
}

.form-row {
  margin-bottom: 24px;
}

.form-row:last-child {
  margin-bottom: 0;
}

:deep(.employee-form .el-form-item) {
  margin-bottom: 0;
}

:deep(.employee-form .el-form-item__label) {
  font-weight: 500;
  padding-right: 10px;
  color: #606266;
}

:deep(.employee-form .el-input) {
  width: 100%;
}

:deep(.employee-form .el-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.employee-form .el-select) {
  width: 100%;
}

:deep(.employee-form .el-date-editor) {
  width: 100%;
}

:deep(.el-dialog__body) {
  padding: 20px 25px;
}
</style>